package xh.server.processors;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.*;
import xh.server.RequestProcessor;

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by Administrator on 2016/6/25.
 */
public abstract class AbstractProcessor implements RequestProcessor {

    protected HttpRequest requestHead;
    protected HttpContent content;

    protected Charset DefaultCharset = Charset.forName("UTF-8");

    public FullHttpResponse process() {

        return defaultResponse("success");
    }

    public FullHttpResponse defaultResponse(String respContent) {

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(respContent.getBytes(DefaultCharset)));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        if (HttpHeaders.isKeepAlive(requestHead)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }

        return response;
    }

    public FullHttpResponse defaultResponse(byte[] bytes) {

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        if (HttpHeaders.isKeepAlive(requestHead)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }

        return response;
    }


    public FullHttpResponse defaultResponse(ByteBuffer bb) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bb));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
        if (HttpHeaders.isKeepAlive(requestHead)) {
            response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
        }

        return response;
    }

    public void setHttpRequest(HttpRequest requestHead, HttpContent content) {
        this.requestHead = requestHead;
        this.content = content;
    }
}
